import logging
from pathlib import Path

import yaml
from wsc_core import models

from utils import glb

courses = yaml.safe_load(Path('chapters.example.yaml').read_text())
# chapters: [['绪论', []], ['线性表', []], ['栈和队列', []], ...]
course_name, chapters = courses[0]
course = models.Course.get_or_none(models.Course.name == course_name)


@glb.db.atomic()
def init():
    global course
    if course:
        logging.error(f'已经存在课程: {course_name}')
        for c in models.Chapter.select().where(models.Chapter.course_uuid == course.uuid):
            chapters[c.name] = [chapters[c.name], c]
    else:
        course = models.Course.create(name=course_name)
        for i, c in enumerate(chapters.keys(), 1):
            chapters[c] = [chapters[c], models.Chapter.create(name=c, course_uuid=course.uuid, index=i)]


init()
